package cn.wen233.srpc.core.spring.server.autoconfigure;

import cn.wen233.srpc.core.spring.server.EnableSunglowServer;
import cn.wen233.srpc.core.sunglow.http.Sunglow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Import导入类
 *
 * @author wenei
 * @date 2021-12-26 14:01
 */
@Slf4j
public class SunglowServerRegistrar implements ImportBeanDefinitionRegistrar {

    private static final String PORT = "port";

    private static final String APP_NAME = "appName";

    private static final String SCANS = "scans";

    private static final String PATH = "path";

    private Class<?> getAnnotationClass() {
        return EnableSunglowServer.class;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(this.getAnnotationClass().getName()));
        assert attributes != null;
        Number port = attributes.getNumber(PORT);
        String appName = attributes.getString(APP_NAME);
        log.info("当前应用appName={}", appName);
        Sunglow.setAppName(appName);
        Sunglow.setPort(port.intValue());
        AnnotationAttributes[] scans = attributes.getAnnotationArray(SCANS);
        List<String> pathList = Arrays.stream(scans).map(x -> x.getString(PATH)).collect(Collectors.toList());
        // 如果scans为空
        if (pathList.isEmpty()) {
            // 被注解的Class名称
            String annotatedClassName = annotationMetadata.getClassName();
            // 获取被注解Class的同级路径
            pathList = Collections.singletonList(annotatedClassName.substring(0, annotatedClassName.lastIndexOf('.')));
        }
        // 添加Exporter Bean 对外暴露接口
        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(Exporter.class);
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues.addPropertyValue(PORT, port.intValue());
        propertyValues.addPropertyValue(SCANS, pathList);
        beanDefinition.setPropertyValues(propertyValues);
        beanDefinitionRegistry.registerBeanDefinition(Exporter.class.getSimpleName(), beanDefinition);
    }
}
